let app_config = require('./app_config.js')
// import store from '@/store'
let app = false
let baseURL = app_config.domain
function request (p) {
    /**
     * passLoading 加载提示，默认false，1不显示
     * showSuccess 接口成功提示，默认false，1显示
     * 
     */
    !app && (app = getApp())
    var params = ''
    if (p.params) {
        params = '?'
        var keyvalPair = ''
        for (var k in p.params) {
            keyvalPair = k + '=' + p.params[k]
            if (params === '?') {
                params += keyvalPair
            } else {
                params += '&' + keyvalPair
            }
        }
        if (params === '?') {
            params = ''
        }
    }
    if (p.url.substr(0, 4) != 'http') {
        p.url = baseURL + p.url + params
    }
    if (!p.method) p.method = 'POST'
    var user_token = app.globalData.user_token || false
    if (!p.data) p.data = {}
    //if (!p.data.user_token) p.data.user_token = user_token
    p.header = { 'Content-Type': 'application/x-www-form-urlencoded' };
    p.header.lang = 'CHN';
    !p.pass_token && user_token && (p.header.token = user_token); //token
    var success_cb = p.success || false
    p.success = (res) => {
        !p.passLoading && setTimeout(() => { uni.hideLoading() }, 300);
        res = res.data || res;
        if (res.code && res.code != 200) {
            if (res.code == 401) {
                app.globalData.user_info = false
                app.globalData.user_token = false
                ZC.clear()
                if (!app_config.debug) {
                    appLogin()
                }
            }
            else if (p.fail) {
                p.fail(res)
            }
        }
        else {
            let successMsg = res.message && res.message !== 'ok' ? res.message : '操作成功'
            p.showSuccess && uni.showToast({ title: successMsg, icon: 'none' });
            if (success_cb) success_cb(res);
        }
    }

    if (!p.fail) p.fail = function (res) {
        !p.passLoading && setTimeout(() => { uni.hideLoading() }, 300);
        // console.log(11111, res)
        if (res.code == 401) {
            app.globalData.user_info = false
            app.globalData.user_token = false
            ZC.clear()
            if (!app_config.debug) {
                appLogin()
            }
        }
        else {
            uni.showToast({
                title: res.message || '未知错误！',
                icon: 'none',
                duration: 2000
            })
        }
    }
    !p.passLoading && uni.showLoading({ title: 'loding...' });
    // console.log('p', p)
    return uni.request(p);
}
function httpGet (p) {
    return new Promise((resolve, reject) => {
        p.method = 'GET'
        p.success = (res) => {
            resolve(res)
        }
        // p.fail = (res)=>{
        // 	reject(res)
        // }
        request(p)
    })
}
function httpPost (p) {
    return new Promise((resolve, reject) => {
        p.method = 'POST'
        p.success = (res) => {
            resolve(res)
        }
        // p.fail = (res)=>{
        // 	reject(res)
        // }
        request(p)
    })
}

Date.prototype.format = function (format) {
    var date = {
        'M+': this.getMonth() + 1,
        'd+': this.getDate(),
        'h+': this.getHours(),
        'm+': this.getMinutes(),
        's+': this.getSeconds(),
        'q+': Math.floor((this.getMonth() + 3) / 3),
        'S+': this.getMilliseconds(),
    }
    if (/(y+)/i.test(format)) {
        format = format.replace(
            RegExp.$1,
            (this.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
    }
    for (var k in date) {
        if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(
                RegExp.$1,
                RegExp.$1.length == 1
                    ? date[k]
                    : ('00' + date[k]).substr(('' + date[k]).length)
            )
        }
    }
    return format
}
function timeToStr (time, format) {
	var _time = Number.isInteger(time)?(~~time * 1000):time
    var d = time ? new Date(_time) : new Date()
    return d.format(format || 'yyyy-MM-dd')
}

let sys_config = false
function get_sys_config (fn) {
    if (sys_config) {
        fn && fn(sys_config)
        return sys_config
    }
    request({
        url: '/api/get_config',
        passLoading: true,
        method: 'GET',
        success: (res) => {
            fn && fn(res.data)
        },
    })
}

function getQueryString (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) return decodeURI(r[2])
    return null
}
function getHashString (name) {
    var reg = new RegExp('(^\\?||&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.hash.substr(1).match(reg)
    if (r != null) return decodeURI(r[2])
    return null
}

let loging = false
let login_fn = []
function appLogin (fn) {
    !app && (app = getApp())

    !app.globalData.user_info && (app.globalData.user_info = ZC('user_info'))
    !app.globalData.user_token && (app.globalData.user_token = ZC('user_token'))
	// console.log(app.globalData.user_info, app.globalData.user_token, loging);
    if (app.globalData.user_info) {
        fn && fn(app.globalData.user_info)
        return
        // store.dispatch('getUserInfo').then(user => {
        // 	console.log(user)
        // })
        // return new Promise(function(resolve, reject){
        // 	fn&&fn(app.globalData.user_info)
        // 	resolve(app.globalData.user_info);
        // })
    }
    if (app.globalData.user_token) {
        uni.$on('userLogin', (user_info) => {
            uni.$off('userLogin')
            fn && fn(user_info)
        })
        return false
    }
    fn && login_fn.push(fn)

    //如果正在登入则等待
    if (loging) return false

    loging = true
    // #ifdef H5
    // 飞书的code在hash后面
    var code = getQueryString('code')
    if (!code) {
        h5_get_code()
		loging = false;
    } else {
        //注册登入
        return uni.request({
            url: baseURL + '/api/h5_login',
            data: {
                code: code,
            },
            success: (res) => {
                res = res.data
                if (res.code == 401) {
                    !app_config.debug && h5_get_code()
                }

                app.globalData.user_info = res.result
                app.globalData.user_token = res.result.token
                ZC('user_info', app.globalData.user_info, -1)
                ZC('user_token', app.globalData.user_token, -1)

                var search = funcUrlDel(location.search.substr(1), 'code')
                return location.replace(
                    location.origin + location.pathname + search + location.hash
                )

                loging = false
                // while (login_fn.length > 0) {
                //     login_fn.pop()(app.globalData.user_info)
                // }
                // login_fn = false
            },
            fail () {
				loging = false
                //!app_config.debug&&h5_get_code()
            },
        })
    }
    // #endif

    // #ifdef MP
    loging = false
    var pages = getCurrentPages()
    var url = pages.length > 0 ? pages[pages.length - 1].$page.fullPath : ''
    uni.setStorageSync('login_back_url', url)
    uni.redirectTo({
        url: '/pages/index/login',
    })
    // #endif

    function h5_get_code () {
        console.log(process.env.NODE_ENV)
        //获取code
        var hash = location.hash.split('?')
        if (hash.length > 1) {
            hash[1] = funcUrlDel(hash[1], 'code')
            hash[1] = funcUrlDel(hash[1], 'state')
        }
        location.href =
            app_config.login_url +
            '&back_url=' +
            encodeURIComponent(location.href)

        // var redirect_uri = encodeURIComponent(location.origin+location.pathname+hash.join('?'))
        // var url = `${app_config.code_url}?redirect_uri=${redirect_uri}&appid=${app_config.appid}`
        // // var url = `https://open.feishu.cn/open-apis/authen/v1/index?redirect_uri=${redirect_uri}&app_id=${app_config.appid}&state=STATE`
        // location.href = url;
    }
}

function isLogin () {
    !app && (app = getApp())
    var is_login = app.globalData.user_token ? true : false
    return is_login
}
// 是否登录
function alertLogin () {
    let hasLogin = isLogin()
    if (!hasLogin) {
        uni.showModal({
            title: '请先登录后操作',
            showCancel: true,
            success: ({ confirm }) => {
                confirm && appLogin();
            }
        })
    }
    return hasLogin;
}
// 接口方法
function checkLogin (option) {
    console.log('com cklg')
    return new Promise((resolve, reject) => {
        httpGet({
            url: 'applypc/getUserInfo',
        })
            .then((res) => {
                if (res.code === 200 && res.data) {
                    console.log('res.data', res.data)
                    ZC('user_info', res.data, 86400)
                    resolve(res)
                }
                reject(false)
            })
            .catch((ret) => {
                reject(ret)
            })
    })
}
// 删除url中某个参数,并跳转
function funcUrlDel (url, name) {
    var query = url
    if (query.indexOf(name) > -1) {
        var obj = {}
        var arr = query.split('&')
        for (var i = 0; i < arr.length; i++) {
            arr[i] = arr[i].split('=')
            obj[arr[i][0]] = arr[i][1]
        }
        delete obj[name]
        query = JSON.stringify(obj)
            .replace(/[\"\{\}]/g, '')
            .replace(/\:/g, '=')
            .replace(/\,/g, '&')
    }
    return query
}

//oss上传图片
function ossUpFile (file, fn) {
    uni.showLoading({
        title: '上传中',
        mask: true,
    })
    request({
        url: app_config.oss_upurl,
        passLoading: 1,
        success: (res) => {
            console.log(file)
            var ext = file.path.split('.')[1] || ''
            var key =
                (res.result.dir || '') +
                new Date().format('yyyyMMddhhmmss') +
                rand(1000, 9999) +
                '.' +
                ext
            // console.log(file,key)

            uni.uploadFile({
                url: app_config.oss_url, //仅为示例，非真实的接口地址
                filePath: file.path,
                name: 'file',
                formData: {
                    OSSAccessKeyId: res.result.accessid,
                    policy: res.result.policy,
                    signature: res.result.signature,
                    expire: res.result.expire,
                    success_action_status: '200',
                    key: key,
                },
                success: () => {
                    fn && fn(app_config.oss_url + '/' + key)
                },
                complete () {
                    uni.hideLoading()
                },
            })
        },
    })
}

function ossUpVideo (file, fn) {
    uni.showLoading({
        title: '上传中',
        mask: true,
    })
    request({
        url: app_config.oss_upurl,
        passLoading: 1,
        success: (res) => {
            var ext = file.name.split('.')[1] || ''
            var key =
                (res.result.dir || '') +
                new Date().format('yyyyMMddhhmmss') +
                rand(1000, 9999) +
                '.' +
                ext
            console.log(file, key)

            uni.uploadFile({
                url: app_config.oss_url, //仅为示例，非真实的接口地址
                filePath: file.path,
                name: 'file',
                formData: {
                    OSSAccessKeyId: res.result.accessid,
                    policy: res.result.policy,
                    signature: res.result.signature,
                    expire: res.result.expire,
                    success_action_status: '200',
                    key: key,
                },
                success: () => {
                    fn && fn(app_config.oss_url + '/' + key)
                },
                complete () {
                    uni.hideLoading()
                },
            })
        },
    })
}

function funDownload (src, filename, is_base64) {
    if (!src) return
    if (is_base64) {
        linkdown(src)
    } else {
        var domImg = document.createElement('img')
        domImg.crossOrigin = 'anonymous' //关键
        domImg.src = src
        domImg.onload = () => {
            // 图片转base64地址
            var canvas = document.createElement('canvas')
            var context = canvas.getContext('2d')
            canvas.width = domImg.naturalWidth
            canvas.height = domImg.naturalHeight
            context.drawImage(domImg, 0, 0)
            // 如果是PNG图片，则canvas.toDataURL('image/png'),'image/jpeg'
            linkdown(canvas.toDataURL('image/png'))
        }
    }
    function linkdown (str) {
        // 创建隐藏的可下载链接
        var eleLink = document.createElement('a')
        eleLink.download = filename
        eleLink.style.display = 'none'
        // 如果是PNG图片，则canvas.toDataURL('image/png')
        eleLink.href = str
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
    }
}

function rand (min, max) {
    return Math.floor(Math.random() * (max - min)) + min
}

//设置分享
function setShare (share = {}, fn) {
    !app && (app = getApp())
    app.$wx.ready(function () {
        //需在用户可能点击分享按钮前就先调用
        app.$wx.updateTimelineShareData({
            title: share.title || app_config.title, // 分享标题
            link: share.link || location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: share.imgUrl || '', // 分享图标
            success: function () {
                // 设置成功
                fn && fn()
            },
        })
        app.$wx.updateAppMessageShareData({
            title:
                share.title ||
                app.globalData.sys_config.title ||
                app_config.title, // 分享标题
            desc: share.desc || '', // 分享描述
            link: share.link || location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: share.imgUrl || app.globalData.sys_config.logo || '', // 分享图标
            success: function () {
                // 设置成功
                fn && fn()
            },
        })
    })
}

var ZC = function (k, v, t) {
    k = 'ZC_f_' + k
    var active_time = 300000
    var now_tme = new Date().getTime()
    if (t === -1) t = 999999999999
    t || (t = active_time)
    if (!v || typeof v == 'function') {
        //读取缓存
        var cache = uni.getStorageSync(k)
        // cache = cache?JSON.parse(cache):0;
        if (cache && cache.expire_time >= now_tme) {
            return cache.value
        } else {
            if (typeof v == 'function') {
                var value = v()
                if (value) {
                    return ZC(k, value) ? value : false
                } else {
                    return false
                }
            } else {
                return false
            }
        }
    } else {
        //设置缓存
        var cache = {
            expire_time: now_tme + t * 1000, //缓存过期时间
            value: v,
        }
        try {
            //uni.setStorageSync(k, JSON.stringify(cache));
            uni.setStorageSync(k, cache)
            return true
        } catch (e) {
            return false
        }
    }
}
ZC.clear = function (k) {
    if (k) {
        k = 'ZC_f_' + k
        uni.removeStorageSync(k)
    } else {
        uni.clearStorageSync()
    }
}

//制作预览
function buildPreview (info, c_w, fn) {
    let _this = this
    let ctx
    let w = 0
    let h = 0
    let bg_img = new Image()
    bg_img.crossOrigin = '*'
    bg_img.onload = () => {
        w = bg_img.naturalWidth
        h = bg_img.naturalHeight
        if (c_w) {
            var img_r = c_w / w
            w = c_w
            h = h * img_r
        }

        // #ifdef H5
        loadImgs(() => {
            buildCanvas()
        })
        // #endif
    }
    bg_img.src = info.bg_img

    function buildCanvas () {
        let canvas = document.createElement('canvas')
        ctx = canvas.getContext('2d')
        let r = w / info.width
        canvas.width = w
        canvas.height = h
        ctx.drawImage(bg_img, 0, 0, w, h)
        for (var i in info.config) {
            var _item = info.config[i]
            if (_item.type == 1) {
                ctx.fillStyle = _item.color
                var _x = 0
                if (_item.align == 1) {
                    ctx.textAlign = 'left'
                    _x = _item.x * r
                } else if (_item.align == 2) {
                    ctx.textAlign = 'center'
                    _x = (_item.x + _item.width * 0.5) * r
                } else if (_item.align == 3) {
                    ctx.textAlign = 'right'
                    _x = (_item.x + _item.width) * r
                }
                ctx.font = _item.size * r + 'px 黑体'
                ctx.fillText(
                    _item.text,
                    _x,
                    (parseInt(_item.y) + parseInt(_item.size)) * r
                )
            } else if (_item.type == 2) {
                ctx.drawImage(
                    _item.img,
                    _item.x * r,
                    _item.y * r,
                    _item.width * r,
                    _item.height * r
                )
            }
        }
        fn && fn(canvas.toDataURL())
    }

    function loadImgs (fn) {
        var img_num = 0
        for (var i in info.config) {
            var _item = info.config[i]
            if (_item.type == 2) {
                img_num++
                _item.img = new Image()
                _item.img.crossOrigin = 'anonymous'
                _item.img.onload = function () {
                    img_num--
                    if (img_num <= 0) fn && fn()
                }
                _item.img.onerror = function () {
                    img_num--
                    if (img_num <= 0) fn && fn()
                }
                _item.img.src = _item.url
            }
        }
        if (img_num <= 0) fn && fn()
    }
}

function pageDiy () {
    get_sys_config((config) => {
        uni.setNavigationBarTitle({
            title: config.web_title,
        })
    })
}

function isArray (a) {
    return Object.prototype.toString.call(a) === '[object Array]'
}

function dataURLToBlob (dataurl) {
    var arr = dataurl.split(',')
    var mime = arr[0].match(/:(.*?);/)[1]
    var bstr = atob(arr[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
}

function timeFormat (param) {
    return param < 10 ? '0' + param : param
}

function timeOut (actEndTime) {
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime()
    // 对结束时间进行处理渲染到页面
    let obj = null
    // 如果活动未结束，对时间进行处理
    if (actEndTime - newTime > 0) {
        let time = (actEndTime - newTime) / 1000
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24))
        let hou = parseInt((time % (60 * 60 * 24)) / 3600)
        let min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60)
        let sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60)
        obj = {
            day: timeFormat(day).toString().split(''),
            hou: timeFormat(hou).toString().split(''),
            min: timeFormat(min).toString().split(''),
            sec: timeFormat(sec).toString().split(''),
        }
    } else {
        // 活动已结束，全部设置为'00'
        obj = {
            day: ['0', '0'],
            hou: ['0', '0'],
            min: ['0', '0'],
            sec: ['0', '0'],
        }
        return false
        // clearInterval(interval);
    }
    var timeList = { day: obj.day, hou: obj.hou, min: obj.min, sec: obj.sec }
    // console.log(timeList)
    return timeList
}

var is_array = function (value) {
    return (
        value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !value.propertyIsEnumerable('length')
    )
}

let throttle_prev = Date.now()
var throttle = function (func, delay) {
    return () => {
        var now = Date.now()
        if (now - throttle_prev >= delay) {
            func()
            throttle_prev = Date.now()
        }
    }
}

let timer1 = null //防抖，
var debounce = function (fn, t) {
    let delay = t || 500
    return function () {
        let args = arguments
        if (timer1) {
            clearTimeout(timer1)
        }
        timer1 = setTimeout(() => {
            fn.apply(this, args)
            timer1 = null
        }, delay)
    }
}

function arraySelect (list, value, key, field) {
    for (var i = 0; i < list.length; i++) {
        if (list[i][key || 'value'] == value) {
            return list[i][field || 'name']
        }
    }
    return ''
}

function imageRadius (url, radius, fn) {
    //圆角矩形
    CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
        var min_size = Math.min(w, h)
        if (r > min_size / 2) r = min_size / 2
        // 开始绘制
        this.beginPath()
        this.moveTo(x + r, y)
        this.arcTo(x + w, y, x + w, y + h, r)
        this.arcTo(x + w, y + h, x, y + h, r)
        this.arcTo(x, y + h, x, y, r)
        this.arcTo(x, y, x + w, y, r)
        this.closePath()
        return this
    }

    // canvas元素, 图片元素
    var canvas = document.createElement('canvas'),
        image = new Image()
    var context = canvas.getContext('2d')

    var draw = function (obj) {
        var _radius = obj.width * radius
            ; (canvas.width = obj.width), (canvas.height = obj.height)
        // 创建图片纹理
        var pattern = context.createPattern(obj, 'no-repeat')
        // 如果要绘制一个圆，使用下面代码
        // context.arc(obj.width / 2, obj.height / 2, Math.max(obj.width, obj.height) / 2, 0, 2 * Math.PI);
        // 这里使用圆角矩形
        context.roundRect(0, 0, obj.width, obj.height, _radius || 0)

        // 填充绘制的圆
        context.fillStyle = pattern
        context.fill()
    }

    image.onload = function () {
        draw(this)
        fn && fn(canvas.toDataURL('image/jpeg', 1.0))
    }
    image.src = url
}

function msg (title, icon, fn, time = 2000) {
    if (typeof icon == 'function') {
        time = fn || 2000
        fn = icon
        icon = 'success'
    }
    uni.showToast({
        title: title,
        icon: icon,
        duration: time,
    })

    fn &&
        setTimeout(function () {
            fn()
        }, time)
}

function numConvert (n, lang) {
	if(lang == 'en'){
		if (n < 1e3) return n;
		if (n >= 1e3 && n < 1e6) return +(n / 1e3).toFixed(1) + "K";
		if (n >= 1e6 && n < 1e9) return +(n / 1e6).toFixed(1) + "M";
		if (n >= 1e9 && n < 1e12) return +(n / 1e9).toFixed(1) + "B";
		if (n >= 1e12) return +(n / 1e12).toFixed(1) + "T";
	}
	else{
		if (n < 1e4) return n;
		if (n >= 1e4 && n < 1e8) return +(n / 1e4).toFixed(1) + "万";
		if (n >= 1e8 && n < 1e12) return +(n / 1e8).toFixed(1) + "亿";
		if (n >= 1e12) return +(n / 1e12).toFixed(1) + "万亿";
	}
}

module.exports = {
    request: request,
    httpGet: httpGet,
    httpPost: httpPost,
    timeToStr: timeToStr,
    app_config: app_config,
    get_sys_config: get_sys_config,
    getQueryString: getQueryString,
    getHashString: getHashString,
    appLogin: appLogin,
    isLogin: isLogin,
    ossUpFile: ossUpFile,
    funDownload: funDownload,
    setShare: setShare,
    ZC: ZC,
    buildPreview: buildPreview,
    pageDiy: pageDiy,
    isArray: isArray,
    dataURLToBlob: dataURLToBlob,
    timeOut: timeOut,
    ossUpVideo: ossUpVideo,
    is_array: is_array,
    throttle: throttle,
    debounce: debounce,
    arraySelect: arraySelect,
    imageRadius: imageRadius,
    msg: msg,
    checkLogin: checkLogin,
    alertLogin: alertLogin,
	numConvert: numConvert
}
